package afcp.alumni.model;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

import afcp.alumni.util.Conf;

public class URL {

	private String urlWithoutParams;
	private Map<String, String> params = new HashMap<>();

	private static Map<String, String> splitQuery(String params) {
		Map<String, String> queryPairs = new LinkedHashMap<>();
		String[] pairs = params.split("&");
		for (String pair : pairs) {
			int idx = pair.indexOf("=");
			try {
				queryPairs.put(URLDecoder.decode(pair.substring(0, idx),
						Conf.DEFAULT_CHARSET_NAME), URLDecoder.decode(
						pair.substring(idx + 1), Conf.DEFAULT_CHARSET_NAME));
			} catch (UnsupportedEncodingException e) {
				// nothing (impossible because Conf class would have failed
				// first)
			}
		}
		return queryPairs;
	}

	public URL(String urlWithoutParams, String params) {
		this.urlWithoutParams = urlWithoutParams;
		if (params != null && !params.isEmpty()) {
			this.params = splitQuery(params);
		}
	}

	public URL(String urlWithoutParams, Map<String, String> params) {
		this.urlWithoutParams = urlWithoutParams;
		this.params = params;
	}

	public URL(String urlWithoutParams) {
		this.urlWithoutParams = urlWithoutParams;
	}

	public URL() {
	}

	public String getUrlWithoutParams() {
		return urlWithoutParams;
	}

	public void setUrlWithoutParams(String urlWithoutParams) {
		this.urlWithoutParams = urlWithoutParams;
	}

	public Map<String, String> getParams() {
		return params;
	}

	public String getParam(String key) {
		return params.get(key);
	}

	public void addParam(String key, String value) {
		params.put(key, value);
	}

	public String getFullUrl() {
		if (params == null || params.isEmpty()) {
			return urlWithoutParams;
		} else {
			StringBuilder sb = new StringBuilder(urlWithoutParams);
			sb.append("?");
			boolean first = true;
			for (Entry<String, String> entry : params.entrySet()) {
				if (first) {
					first = false;
				} else {
					sb.append("&");
				}
				try {
					sb.append(
							URLEncoder.encode(entry.getKey(),
									Conf.DEFAULT_CHARSET_NAME))
							.append("=")
							.append(URLEncoder.encode(entry.getValue(),
									Conf.DEFAULT_CHARSET_NAME));
				} catch (UnsupportedEncodingException e) {
					// nothing (impossible because Conf class would have failed
					// first)
				}
			}
			return sb.toString();
		}
	}

}
